package com.sky.controller.admin.dish;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品管理")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @PostMapping
    @ApiOperation(value = "新增菜品")
    public Result save(@RequestBody DishDTO dto) {
        dto.setStatus(1);
        dishService.saveWithFlavor(dto);
//        由于新增了菜品,对应的这个分类里的信息就会变.得删除这个分类的缓存
        String key="dish_"+dto.getCategoryId();
        stringRedisTemplate.delete(key);
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页查询菜品")
    public Result<PageResult> pageQuery(DishPageQueryDTO dish) {

        return Result.success(dishService.pageQuery(dish));
    }

    @DeleteMapping
    @ApiOperation(value = "批量删除菜品")
    public Result delete(@RequestParam List<Long> ids) {
        dishService.deleteBatch(ids);
//        为了方便,直接删除所有菜品缓存
        clearcache();
        return Result.success();
    }
    @PostMapping("/status/{status}")
    @ApiOperation(value = "修改菜品状态")
    public Result updateStatus(@PathVariable int status,Long id) {
        System.out.println(status+"   "+id);
        dishService.updateStatus(status,id);
        clearcache();
        return Result.success();
    }

    private void clearcache() {
        //        为了方便,直接删除所有菜品缓存
        Set<String> keys = stringRedisTemplate.keys("dish_*");
        if (keys != null) {
            stringRedisTemplate.delete(keys);
        }
    }

    @GetMapping("/list")
    @ApiOperation(value = "根据分类id查询菜品")
    public Result<List<Dish>> getById( Long categoryId) {
        System.out.println("根据分类id查询菜品");
        System.out.println(categoryId);
        return Result.success(dishService.getById(categoryId));
    }
    @PutMapping
    @ApiOperation(value = "修改菜品")
    public Result update(@RequestBody DishDTO dto) {
        dishService.update(dto);
        //        为了方便,直接删除所有菜品缓存
        clearcache();
        return Result.success();
    }
}
